package com.zeus.core.rule;

import com.zeus.common.enums.ZeusAlarmLevelEnum;
import com.zeus.common.utils.TimeUtils;
import com.zeus.core.context.ZeusContext;

import java.util.Optional;

/**
 * 聚合规则-阈值 抽象类
 *
 * @author f1ybear_wang  2022/3/23 5:53 下午
 */
public abstract class AbstractGatherRuleThreshold extends AbstractGatherRule {

    public AbstractGatherRuleThreshold() {
        super();
        this.levelEnum = ZeusAlarmLevelEnum.P4;
    }

    @Override
    public void addCount() {
        super.addCount();

        // 刷新级别
        refreshLevel();
    }

    @Override
    public boolean isTimeout() {
        if (this.lastDate == null) {
            return true;
        }
        // 分钟
        final int thresholdTime = ZeusContext.getContext().getThresholdTime();

        final long timeInterval = System.currentTimeMillis() - this.lastDate;
        return TimeUtils.minuteToMilliseconds(thresholdTime) < timeInterval;
    }

    @Override
    public void sendMessageSuccess() {
        super.sendMessageSuccess();
    }

    @Override
    public void setAlarmLevel(ZeusAlarmLevelEnum alarmLevel) {
        // 忽略
    }

    @Override
    public void setAlarmLevel(String... keyWorlds) {
        // 忽略
    }

    /**
     * 刷新报警级别
     *
     * @author f1ybear_wang  2022/3/1 2:44 下午
     */
    private void refreshLevel() {
        // 根据连续发生次数进行报警等级刷新

        // 获取当前告警级别
        ZeusAlarmLevelEnum levelEnum = Optional.ofNullable(this.levelEnum).orElse(ZeusAlarmLevelEnum.P4);

        // 如果当前次数大于等于阈值时，则提高等级
        if (ZeusContext.getContext().getThresholdNumber(levelEnum.getNext()) <= this.count.get()) {
            this.levelEnum = levelEnum.getNext();
        }
    }

}
